import React, { Component } from 'react';

import Header from '../../core/components/header';
import Table from '../../core/components/table';
import { Get } from '../../core/utils/fetch';
import Dialog from '../../core/utils/dialog';

import UserEdit from './components/edit';

class User extends Component {

    state = {
        url: '',
        roleDataMap: {},
        showEditId: '',
        showEdit: false,
    };

    componentDidMount = () => {
        Get(`/api/enums/Role`)
            .then((r) => {
                let m = {};
                r.forEach((item) => {
                    let k = Object.keys(item)[0];
                    m[k] = item[k];
                });
                this.setState({url: '/spi/user', roleDataMap: m});
            });
    };

    close = () => {
        this.setState({
            showEdit: false
        });
    }

    render = () => {
        let columns = [
            { title: '序号', name: 'id' },
            { title: '账号名称', name: 'loginName' },
            { title: '使用人员', name: 'userName' },
            { title: '联系方式', name: 'mobilePhone' },
            { title: '角色', render: this.renderRole },
            { title: '操作', render: this.renderOpertion },
        ];
        return (
            <div>
                <Header title="系统管理" subTitle="System Manage"></Header>
                <Table
                    ref="table"
                    title="账号管理"
                    subTitle={<button type="button" className="btn btn-sm btn-primary btn-add" onClick={() => this._onAdd()}>新增</button>}
                    url={this.state.url}
                    columns={columns} >
                </Table>
                <UserEdit isShow={this.state.showEdit} id={this.state.showEditId} onEdit={this._refresh} onClose={this.close} />
            </div>
        );
    };

    renderRole = (dataItem) => {
        let {roleDataMap} = this.state;
        return roleDataMap[dataItem.role];
    };

    renderOpertion = (dataItem) => {
        return (
            <div>
                <a onClick={() => this._onAdd(dataItem.id)}>编辑</a>
                {'    '}
                <a onClick={() => this._onDel(dataItem.id)}>删除</a>
            </div>
        );
    };

    _onAdd = (showEditId) => {
        this.setState({ 'showEdit': true, showEditId });
    };

    _onDel = (id) => {
        Dialog.confirm('你确定要删除吗', () => {
            Get(`/spi/user/del/${id}`)
                .then(() => {
                    this._refresh();
                });
        });
    };

    _refresh = () => {
        this.refs.table.refresh();
    };
}

export default User;